/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.context;

import com.jb.web.application.PageSecurityException;
import com.jb.web.lifecycle.LifeCycleImpl;

import com.jb.faces.FacesException;
import com.jb.faces.context.FacesContext;
import com.jb.faces.context.FacesContextFactory;
import com.jb.faces.lifecycle.Lifecycle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * Implementation of FacesContextFactory. Create a WebContext.
 */
public class WebContextFactory extends FacesContextFactory {
    private Log log = LogFactory.getLog(getClass().getName());
    
    public FacesContext getFacesContext( Object request, Object response, Lifecycle lifecycle)
        throws FacesException {
        if (!(request instanceof HttpServletRequest)) {
            throw new FacesException("Request type not supported");
        }

        if (!(response instanceof HttpServletResponse)) {
            throw new FacesException("Response type not supported");
        }

        try {
            WebContext webContext = new WebContext((HttpServletRequest) request, (HttpServletResponse) response);
           // webContext.initialize();
            if(lifecycle instanceof LifeCycleImpl)
            ((LifeCycleImpl) lifecycle).init(webContext);

            return webContext;
        } catch (PageSecurityException e) {
            throw e;
        } catch (FacesException e) {
            if (log.isFatalEnabled()) {
                log.fatal(this, e);
            }

            throw e;
        } catch (Exception _e) {
            if (log.isFatalEnabled()) {
                log.fatal(this, _e);
            }

            throw new FacesException(_e);
        }
    }
}
